##
# Author: Samuel Abels <http://debain.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##
import os
import pango
import gobject
import gtk
import util
from gettext  import gettext as _
from config   import c as cfg
from Workflow import Workflow

class WorkflowSelector(gobject.GObject):
    def __init__(self, controller, show_edit_button = False):
        gobject.GObject.__init__(self)
        self.controller            = controller
        gladefile                  = cfg['APP_SYSNAME'] + '.glade'
        dialogname                 = 'dialog_select_workflow'
        self.xml                   = util.get_glade_xml(gladefile, dialogname)
        self.window                = self.xml.get_widget(dialogname)
        self.entry_search          = self.xml.get_widget('entry_search')
        self.button_edit_workflow  = self.xml.get_widget('button_edit_workflow')
        self.button_use_workflow   = self.xml.get_widget('button_use_workflow')
        hide_deleted               = 'checkbutton_hide_deleted'
        self.hide_deleted          = self.xml.get_widget(hide_deleted)
        callback                   = self._treeview_selection_changed_cb
        self.treeview              = self.xml.get_widget('treeview_workflow')
        self.treeview_selection    = self.treeview.get_selection()
        self.treeview_selection_hd = self.treeview_selection.connect('changed',
                                                                     callback)

        self.xml.signal_autoconnect(self)
        self.window.connect('response', self._on_window_response)
        self.treeview.connect('row-activated', self._treeview_row_activated)
        self.window.show_all()
        if not show_edit_button:
            self.button_edit_workflow.hide()

        self.model = gtk.ListStore(gobject.TYPE_PYOBJECT,
                                   gobject.TYPE_STRING)
        
        renderer = gtk.CellRendererText()
        column   = gtk.TreeViewColumn(_("Workflow"), renderer, markup = 1)
        column.set_sort_column_id(1)
        column.set_resizable(True)
        column.set_expand(True)
        self.treeview.append_column(column)

        self.treeview.set_model(self.model)
        self.treeview.set_headers_clickable(True)
        self.treeview.set_rules_hint(True)
        self.model.set_sort_column_id(1, gtk.SORT_ASCENDING)

        self._update_workflows()


    def hide(self):
        self.window.hide()


    def destroy(self):
        self.window.destroy()


    def _update_workflows(self):
        # Create a list of workflows that match.
        visible_workflows = [row[0] for row in self.model]
        search_term       = '%' + self.entry_search.get_text() + '%'
        show_deleted      = not self.hide_deleted.get_active()
        db                = self.controller.workflow_db
        show_workflows    = db.find_workflow(search_term, show_deleted)

        # Hide any workflows that do not match.
        remove_iters = []
        for n, workflow in enumerate(visible_workflows):
            if workflow in show_workflows:
                continue
            remove_iters.append(self.model.get_iter(n))
        for iter in remove_iters:
            self.model.remove(iter)

        # Add any items that match but aren't yet visible.
        for workflow in show_workflows:
            if workflow in visible_workflows:
                continue
            name  = workflow.get_name()
            descr = workflow.get_summary()
            if workflow.is_deleted():
                text  = '%s\n%s' % (name, descr)
            else:
                text  = '<span weight="bold">%s</span>\n%s' % (name, descr)
            iter  = self.model.append()
            self.model.set_value(iter, 0, workflow)
            self.model.set_value(iter, 1, text)

        if len(show_workflows) > 0:
            self.treeview_selection.select_iter(self.model.get_iter_first())


    def _treeview_selection_changed_cb(self, selection):
        model, iter = self.treeview_selection.get_selected()
        if not iter:
            self.button_edit_workflow.set_sensitive(False)
            self.button_use_workflow.set_sensitive(False)
            return
        self.button_edit_workflow.set_sensitive(True)
        self.button_use_workflow.set_sensitive(True)

        self.treeview_selection.handler_block(self.treeview_selection_hd)
        # we may do something here.
        self.treeview_selection.handler_unblock(self.treeview_selection_hd)


    def _entry_search_changed_cb(self, widget):
        self._update_workflows()


    def _treeview_row_activated(self, widget, row, column):
        self.button_use_workflow.clicked()


    ################################################################
    # Callbacks.
    ################################################################
    def _on_window_response(self, window, response):
        if response < 0:
            return self.emit('cancel')

        model, iter = self.treeview_selection.get_selected()
        workflow    = model.get_value(iter, 0)
        if response == 1:
            return self.emit('edit', workflow)
        self.emit('select', workflow)


    def _checkbutton_hide_deleted_toggled_cb(self, button):
        self._update_workflows()


    def _button_use_workflow_clicked_cb(self, button):
        pass

gobject.type_register(WorkflowSelector)

gobject.signal_new('cancel',
                   WorkflowSelector,
                   gobject.SIGNAL_RUN_FIRST,
                   gobject.TYPE_NONE,
                   ())

gobject.signal_new('edit',
                   WorkflowSelector,
                   gobject.SIGNAL_RUN_FIRST,
                   gobject.TYPE_NONE,
                   (gobject.TYPE_PYOBJECT,))

gobject.signal_new('select',
                   WorkflowSelector,
                   gobject.SIGNAL_RUN_FIRST,
                   gobject.TYPE_NONE,
                   (gobject.TYPE_PYOBJECT,))
